//
//  Authorization.m
//  FaceCheck
//
//  Created by CityDo on 2018/6/23.
//  Copyright © 2018年 CityDo. All rights reserved.
//

#import "CitydoCheckAuthorization.h"
#import <CommonCrypto/CommonHMAC.h>

#define security_check_API_KEY @"app_zlx"
#define security_check_API_SECRET @"39f5a7cc-3eb6-4zlx-9394-8e92f8c873d5"

@implementation CitydoCheckAuthorization

+ (NSString *) encode {
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    NSInteger time = [[NSNumber numberWithDouble:timeInterval] integerValue];
    NSString *timestamp = [NSString stringWithFormat:@"%ld",(long)time];
    
    //2、生成随机数
    NSString *nonce = [self randomString];
    
    //3、将timestamp、nonce、API_KEY 这三个字符串”依据字符串首位字符的ASCII码“进行升序排列，并join成一个字符串
    NSArray *sortArr = [[NSArray alloc]initWithObjects:timestamp,nonce,security_check_API_KEY, nil];
    
    NSString *joinStr = [self sortStringArr:sortArr];
    
    //4、用API_SECRET对这个字符串join_str做hmac-sha256 签名，且以16进制编码
    NSString *signature = [self gethmacSHA256StringWithKey:security_check_API_SECRET stringData:joinStr];
    
    //5、将上述的值按照 #{k}=#{v} 并以 ',' join在一起，获取签名认证字符串
    //注：authorization即为最终结果，将该签名认证字符串赋值给HTTP HEADER 的 Authorization 中，完成一次接口访问
    return [NSString stringWithFormat:@"API_KEY=%@,timestamp=%@,nonce=%@,signature=%@", security_check_API_KEY, timestamp, nonce, signature];
    
}

+ (NSDictionary *) encodeParams {
    NSString *cityDOSDK_API_KEY =@"";
    NSString *cityDOSDK_API_SECRET =@"";
    
    //    [CityDOSDK initCityDOSDK].cityDOSDK_API_KEY = @"app_zlx";
    //    [CityDOSDK initCityDOSDK].cityDOSDK_API_SECRET = @"39f5a7cc-3eb6-4zlx-9394-8e92f8c873d5";
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    NSInteger time = [[NSNumber numberWithDouble:timeInterval] integerValue]*1000;//乘以1000 用毫秒统计
    NSString *timestamp = [NSString stringWithFormat:@"%ld",(long)time];
    
    //2、生成随机数
    NSString *nonce = [self randomString];
    NSString *joinStr;
    NSArray *sortArr;
    NSString *signature;
    NSDictionary *params;
    NSMutableDictionary *paramsDict;
    //测试工具，跨应用取值
    //上架前需要修改下面部分
    NSString *apikeytext =   @"";
    NSString *apiSecretText =  @"";
    
    if ([apikeytext isEqualToString:@""]||apikeytext == nil) {
        apikeytext = cityDOSDK_API_KEY;
    }
    
    if ([apiSecretText isEqualToString:@""]||apiSecretText == nil) {
        apiSecretText = cityDOSDK_API_SECRET;
    }
    
    if ([cityDOSDK_API_KEY isEqualToString:@""]||cityDOSDK_API_KEY == nil) {
        cityDOSDK_API_KEY =apikeytext;
    }
    
    if ([cityDOSDK_API_SECRET isEqualToString:@""]||cityDOSDK_API_SECRET == nil) {
        cityDOSDK_API_SECRET = apiSecretText;
    }
    
    if ([apikeytext isEqualToString:@""]||apikeytext == nil) {
        //3、将timestamp、nonce、API_KEY 这三个字符串”依据字符串首位字符的ASCII码“进行升序排列，并join成一个字符串
        sortArr = [[NSArray alloc]initWithObjects:timestamp,nonce,security_check_API_KEY, nil];
        joinStr = [self sortStringArr:sortArr];
        params = @{@"API_KEY":security_check_API_KEY,@"timestamp":timestamp,@"nonce":nonce,@"signature":@""};
    } else {
        sortArr = [[NSArray alloc]initWithObjects:timestamp,nonce,apikeytext, nil];
        joinStr = [self sortStringArr:sortArr];
        params = @{@"API_KEY":apikeytext,@"timestamp":timestamp,@"nonce":nonce,@"signature":@""} ;
    }
    
    paramsDict = [params mutableCopy];
    if ([apiSecretText isEqualToString:@""]||apiSecretText == nil) {
        
        signature = [self gethmacSHA256StringWithKey:security_check_API_SECRET stringData:joinStr];
        [paramsDict setValue:security_check_API_SECRET forKey:@"API_SECRET"];
        
    } else {
        signature = [self gethmacSHA256StringWithKey:apiSecretText stringData:joinStr];
        [paramsDict setValue:apiSecretText forKey:@"API_SECRET"];
    }
    
    [paramsDict setValue:signature forKey:@"signature"];
    
    //4、用API_SECRET对这个字符串join_str做hmac-sha256 签名，且以16进制编码
    
    //5、将上述的值按照 #{k}=#{v} 并以 ',' join在一起，获取签名认证字符串
    //注：authorization即为最终结果，将该签名认证字符串赋值给HTTP HEADER 的 Authorization 中，完成一次接口访问
    
    //上架前需要修改下面部分
    return paramsDict;
}

//生成随机字符串
+ (NSString *)randomString {
    NSString *uuidStr = [[NSUUID UUID] UUIDString];
    NSString *nonceStr = [uuidStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return nonceStr;
}

//对数组进行排序
+ (NSString *)sortStringArr:(NSArray *)array {
    if (array.count != 3) {
        return @"";
    }
    NSStringCompareOptions comparisonOptions = NSLiteralSearch;//区分大小写比较
    NSComparator sort = ^(NSString *obj1, NSString *obj2) {
        NSRange range = NSMakeRange(0, obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [array sortedArrayUsingComparator:sort];
    //将排序后的结果拼接为一个字符串
    NSString *result = [[resultArray valueForKey:@"description"] componentsJoinedByString:@""];
    return result;
}

//用API_SECRET对join_str做hamc-sha256签名，且以16进制编码，可用下面方式实现：
+ (NSString *)gethmacSHA256StringWithKey:(NSString *)key stringData:(NSString *)stringData {
    const char *keyData = key.UTF8String;
    const char *strData = stringData.UTF8String;
    unsigned char buffer[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer);
    NSMutableString *strM = [NSMutableString string];
    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [strM appendFormat:@"%02x", buffer[i]];
    }
    return [strM copy];
}
@end
